﻿using System.Data.SqlClient;
using System.Diagnostics;
using System.IO;
using System.Reflection;

namespace GeneratorStudio.Tests
{
    public static class TestUtilities
    {
        public static void KillDBProcesses(string connectionString, string database)
        {
            using (var sqlConnection = new SqlConnection())
            {
                sqlConnection.ConnectionString = connectionString;
                sqlConnection.Open();
                sqlConnection.ChangeDatabase("master");
                var sqlCommand = new SqlCommand
                                     {
                                         Connection = sqlConnection,
                                         CommandText =
                                             (@"
                            Declare @dbid int,
                                    @spid int,
                                    @str nvarchar(128)
                            select @dbid = dbid from master..sysdatabases
                              where name = '" + database + @"'
                            declare spidcurs cursor for
                               select spid from master..sysprocesses where dbid = @dbid
                            open spidcurs
                            fetch next from spidcurs into @spid
                            While @@fetch_status = 0
                              Begin
                                Select @str = 'kill '+convert(nvarchar(30),@spid)
                                exec(@str)
                                --print @str
                                fetch next from spidcurs into @spid
                            End
                            deallocate spidcurs            
                            ")
                                     };
                sqlCommand.ExecuteNonQuery();
                sqlConnection.Close();
            }
        }
        
        public static void SaveSqlScriptToDisk()
        {
            var assembly = Assembly.GetExecutingAssembly();
            Stream stream = assembly.GetManifestResourceStream("GeneratorStudio.Tests.Resources.testdb.sql");
            var data = new byte[stream.Length];
            stream.Read(data, 0, data.Length);
            File.WriteAllBytes("testdb.sql", data);
        }

        public static void RunDOSCommand(string commandLine)
        {
            System.Threading.Thread.Sleep(100);
            var psi = new ProcessStartInfo("CMD.EXE", "/C " + commandLine)
                          {
                              CreateNoWindow = true
                          };
            System.Diagnostics.Process p = Process.Start(psi);
            p.WaitForExit();
        }
    }
}
